package com.markhsiu.MiniMQ.remote.transport.netty.handler;

import com.markhsiu.MiniMQ.broker.message.BrokerFactory;
import com.markhsiu.MiniMQ.model.Message;
import com.markhsiu.MiniMQ.model.Result;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Mark Hsiu on 2017/2/8.
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter{


    //管道链路激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	 super.channelActive(ctx);
    }

    // 当服务器端返回应答消息时，channelRead方法被调用，Netty的ByteBuf中读取并打印应答消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        Result result =  BrokerFactory.instance().getCallBack(message.getMessageID());
        if(result == null){
            throw new RuntimeException("系统错误");
        }
        
        result.setMessage(message);
        result.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 释放资源
        ctx.close();
    }
}
